import React, { useEffect, useState, useMemo } from 'react';
import { Space, Table, Tag, Button, Modal } from 'antd';
import '../styles/index.css';
import { history } from 'umi';
import axios from '../axios';
export default function roomManage() {
  const [name, setName] = useState('');
  const [cate, setCate] = useState('');
  const [flag, setFlag] = useState(false);
  const [datas, setDatas] = useState([]);
  const [update, setUpdate] = useState(false);
  const columns = [
    {
      title: '序号',
      dataIndex: 'order',
      key: 'order',
    },
    {
      title: '组织机构名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '人数',
      dataIndex: 'employees',
      key: 'employees',
    },
    // {
    //   title: '创建时间',
    //   dataIndex: 'buildtime',
    //   key: 'buildtime',
    // },
    {
      title: '修改时间',
      dataIndex: 'changetime',
      key: 'changetime',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: any) => (
        <div>
          {status === true ? (
            <span style={{ color: 'green' }}>已启用</span>
          ) : (
            <span style={{ color: 'red' }}>已禁用</span>
          )}
        </div>
      ),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      render: (status: any) => {
        return (
          <div>
            <span className="hwy-edit">编辑</span>
            <span className="hwy-edit">删除</span>
            {status === true ? (
              <span className="hwy-edit">禁用</span>
            ) : (
              <span className="hwy-edit">启用</span>
            )}
          </div>
        );
      },
    },
  ];

  const [organization, setOrganization] = useState([]);
  const getOrganization = async () => {
    let {
      data: { data },
    } = await axios.get('/getOrganization');
    setOrganization(data);
    // console.log(data)
  };
  const deleteOrganization = async (_id: any) => {
    let data = await axios.post('/deleteOrganization', { _id });
    setUpdate(!update);
  };

  const deleteDepartment = async (_id: any) => {
    let data = await axios.post('/deleteDepartment', { _id });
    setUpdate(!update);
  };

  useEffect(() => {
    getOrganization();
  }, [update]);

  const searchlist = useMemo(() => {
    // console.log(1111)
    console.log(flag);
    let searchlist: any = [...organization];
    if (name) {
      console.log(11);
      console.log(name);
      searchlist = organization.filter((item: any) => item.name.includes(name));
    }
    if (cate) {
      console.log(22);

      searchlist = organization.filter((item: any) => item.type == cate);
    }
    if (cate && name) {
      console.log(33);
      searchlist = organization.filter(
        (item: any) => item.name.includes(name) && item.type == cate,
      );
    }
    let datalist: any = [];
    searchlist.map((item: any, index: number) => {
      datalist.push({
        key: index,
        order: index + 1,
        name: item.name,
        type: item.type,
        employees: item.employees,
        // buildtime:item.buildtime.split('T')[0],
        changetime: item.changetime.split('T')[0],
        status: item.status,
        operation: item.status,
        _id: item._id,
      });
    });
    setDatas(datalist);
    // setFlag(false)
  }, [flag, organization]);

  const changeStatus = async (_id: any, status: any) => {
    let data = await axios.post('/changeStatus', { _id, status });
    getOrganization();
  };
  useEffect(() => {
    getOrganization();
  }, []);

  //  编辑
  const [modal1Open, setModal1Open] = useState(false);
  const [modal2Open, setModal2Open] = useState(false);
  const [_id, setId] = useState('');
  // const [name, setName] = useState('');
  const [addname, setAddname] = useState('');
  const [type, setType] = useState('');
  const [employees, setEmployees] = useState('');
  const [pid, setPid] = useState('');
  const [desc, setDesc] = useState('');
  const [status, setStatus] = useState('');
  const [ogr, setOgr] = useState([]);
  const getOgr = async () => {
    let {
      data: { data },
    } = await axios.get('/getOrganization');
    setOgr(data);
  };
  useEffect(() => {
    getOgr();
  }, []);
  const clean = () => {
    setAddname('');
    setType('');
    setEmployees('');
    setPid('');
    setDesc('');
    setStatus('');
  };
  const updateogrinfo = async () => {
    setUpdate(!update);
    let data = await axios.post('/updateOrganization', {
      _id,
      addname,
      type,
      employees,
      pid,
      desc,
      status,
    });
    setModal1Open(false);
  };

  return (
    <div>
      <div className="hwy-search-box">
        <div>
          <span>机构名称：</span>
          <input
            type="text"
            placeholder="输入部门名称"
            value={name}
            onChange={(e) => {
              setName(e.target.value);
            }}
          />
        </div>
        <div>
          <span>类型：</span>
          <select
            className="hwy-search-select"
            value={cate}
            onChange={(e) => {
              setCate(e.target.value);
            }}
          >
            <option value="">请选择</option>
            <option value="总公司">总公司</option>
            <option value="分公司">分公司</option>
            <option value="部门">部门</option>
          </select>
        </div>
        <div>
          <Button
            className="hwy-search-btn1"
            type="primary"
            onClick={() => setFlag(!flag)}
          >
            查询
          </Button>
          <Button
            onClick={() => {
              console.log(flag, name, cate);
              setName('');
              setCate('');
            }}
          >
            重置
          </Button>
        </div>
      </div>

      <div className="hwy-table-box">
        <div className="hwy-add-box">
          <button
            className="hwy-add-btn1"
            onClick={() => {
              history.push('/home/management/roomManage/addOrganization');
            }}
          >
            新建机构
          </button>
          <div>
            <button className="hwy-add-btn2">导入</button>
            <button className="hwy-add-btn1">导出</button>
          </div>
        </div>

        <div>
          <Table
            columns={columns}
            dataSource={datas}
            pagination={{
              showTotal: (total, range) => `共${total}条`,
              pageSizeOptions: ['5', '10', '15', '20'],
              showSizeChanger: true,
            }}
            onRow={(record: any) => {
              return {
                onClick: (event: any) => {
                  if (
                    event.target.innerText === '禁用' ||
                    event.target.innerText === '启用'
                  ) {
                    changeStatus(record._id, !record.status);
                    // console.log(!record.status)
                  }
                  if (event.target.innerText === '编辑') {
                    setId(record._id);
                    setAddname(record.name);
                    setType(record.type);
                    setEmployees(record.employees);
                    setPid(record.pid);
                    setDesc(record.desc);
                    setStatus(record.status);
                    setModal1Open(true);

                    setModal2Open(true);
                  }
                  if (event.target.innerText === '删除') {
                    if (record.type === '分公司') {
                      deleteOrganization(record._id);
                    }
                    if (record.type === '部门') {
                      deleteDepartment(record._id);
                    }
                  }
                },
              };
            }}
          />
        </div>

        <div>
          <Modal
            title="编辑机构"
            centered
            open={modal2Open}
            onOk={() => {
              updateogrinfo();
              setModal2Open(false);
            }}
            onCancel={() => {
              clean();
              setModal2Open(false);
            }}
          >
            <div>
              <div className="hwy-addOrganization">
                机构名称:
                <input
                  value={addname}
                  onChange={(e) => setAddname(e.target.value)}
                />
                <br />
                机构类型:
                <select
                  value={type}
                  onChange={(e) => {
                    setType(e.target.value);
                  }}
                >
                  <br />
                  <option value="总公司">总公司</option>
                  <option value="分公司">分公司</option>
                  <option value="部门">部门</option>
                </select>
                <br />
                机构人数:
                <input
                  value={employees}
                  onChange={(e) => setEmployees(e.target.value)}
                />
                <br />
                上级机构:{' '}
                <select value={pid} onChange={(e) => setPid(e.target.value)}>
                  {ogr
                    .filter(
                      (item: any) =>
                        item.type === '分公司' || item.type === '总公司',
                    )
                    .map((item: any) => {
                      return <option value={item._id}>{item.name}</option>;
                    })}
                </select>
                <br />
                描述:{' '}
                <input value={desc} onChange={(e) => setDesc(e.target.value)} />
                <br />
                状态:
                <select
                  value={status}
                  onChange={(e) => setStatus(e.target.value)}
                >
                  <option value="true">已启用</option>
                  <option value="false">已禁用</option>
                </select>
              </div>
            </div>
          </Modal>
        </div>
      </div>
    </div>
  );
}
